use std::rc::{Rc,Weak};
use std::cell::RefCell;
use std::sync::{Arc,Mutex};
use std::thread;
// 智能指针


// 使用RefCell<Rc<>> 创建树
#[derive(Debug)]
pub struct Node<T> {
    val:T,
    //使用 weak防止循环引用
    parent:RefCell<Weak<Node<T>>>,
    childrn:RefCell<Vec<Rc<Node<T>>>>
}
 impl <T> Node<T> {
    pub fn new(val:T)->Rc<Self>{
        Rc::new(Node{
            val,
            parent:RefCell::new(Weak::new()),
            childrn:RefCell::new(Vec::new())
        })
    }

    pub fn add_child(self:&Rc<Self>,child:&Rc<Node<T>>) {
        self.childrn.borrow_mut().push(child.clone());
        *child.parent.borrow_mut() = Rc::downgrade(self)
    }
 }

pub fn tree_demo() {
    let root = Node::new(1);
    let child1 = Node::new(2);
    let child2 = Node::new(3);
    root.add_child(&child1);
    root.add_child(&child2);
    child1.add_child(&Node::new(4));
    println!("{:#?}", root);
}

pub fn arc_demo() {
    let shared = Arc::new(Mutex::new(0));
    let mut handles = vec![];
    for _ in 0..10{
        let s = Arc::clone(&shared);
        handles.push(thread::spawn(move || {
            let mut guard = s.lock().unwrap();
            println!("正在执行：{}",*guard);
            *guard +=1;
        }));
    }
    println!("正在执行主线程");
    for ele in handles {
        ele.join().unwrap();
    }

    println!("shared: {}",*shared.lock().unwrap())
}